<?php
namespace app\common\library\helper;

use app\common\exception\NException;

/**
 * Class FileHelper
 * @package app\admin\controller
 * @desc 上传文件类
 */

class FileHelper{

    Const COMPRESS_TRUE  = true;        //是否压缩：是
    Const COMPRESS_FALSE = false;       //是否压缩：否

    /**
     * @param string $name
     * @return array
     * @throws NException
     */
    public static function fileUpload( $name = 'file'){

        $file = request()->file( $name );

        //文件上传
        $res_upload = self::_fileArrUpload( $file );


        $res = [];

            foreach( $res_upload as $key => $val ){

                $res[] = [
                    'path'         => $val[ 'path' ],
                    'name'         => $val['filename_full'],
                    'type'         => $val['file_ext']
                ];

            }
        return $res;
    }

    /**
     * @desc 文件上传（多文件支持）
     * @param $file
     * @return array
     * @throws NException
     */
    private static function _fileArrUpload( $file ){

        $res = [];

        if( is_array( $file ) ){

            foreach( $file as $key => $val ){

                $res[] = self::_fileUpload( $val );

            }

        }else{

            $res[] = self::_fileUpload( $file );

        }

        return $res;

    }

    /**
     * @param \think\File $file
     * @return array
     * @throws NException
     */
    private static function _fileUpload( $file ){

        if( ! $file ){
            throw new NException( '缺少上传文件' );
        }

        $folder_path      = '/uploadFiles';
        $folder_path_real = 'public' . DS . 'uploadFiles';

        $info = $file
//            ->validate( [ 'size' => 4096 * 1000, 'ext' => 'jpg,png,jpeg' ] )
            ->move( ROOT_PATH . $folder_path_real );



        if( ! $info ){
            throw new NException( $file->getError() );
        }


        $path_real              = $info->getRealPath();
        $path_real_folder       = substr( $path_real, 0, strrpos( $path_real, DS ) );
        $path                   = $folder_path . DS . $info->getSaveName();
        $path_folder            = substr( $path, 0, strrpos( $path, DS ) );
        $infos = $info->getInfo();
        // 源文件名
        $filename_full          = $infos['name'];
        $filename               = substr( $filename_full, 0, strpos( $filename_full, '.' ) );
        $file_ext               = $info->getExtension();

        $res = [
            'path_real'         => $path_real,
            'path_real_folder'  => $path_real_folder,
            'path'              =>str_replace('\\','/',$path),
            'path_folder'       => $path_folder,
            'filename_full'     => $filename_full,
            'filename'          => $filename,
            'file_ext'          => $file_ext
        ];

        return $res;

    }



}